﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using FamilyBook.Core.Entities;

namespace FamilyBook.Core.Services
{
    public class UserService
    {
        private readonly GeneralService<User, int> _userGenService;

        public UserService(GeneralService<User, int> userGenService)
        {
            _userGenService = userGenService;
        }

        public User Create(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            user.Password = GetPasswordHash(user.Password, user.Name);
            return _userGenService.Create(user);
        }

        public User GetDetails(int userId)
        {
            return _userGenService.GetDetails(userId);
        }

        public void Update(User user)
        {
            _userGenService.Update(user);
        }

        public bool VerifyUser(string userName, string password)
        {
            User user = _userGenService.GetItemsList().FirstOrDefault(x => x.Name == userName);
            if (user == null)
                return false;

            string pswHash = GetPasswordHash(password, userName);
            return (user.Password == pswHash);
        }

        private string GetPasswordHash(string password, string salt)
        {
            if (string.IsNullOrEmpty(password))
                return null;

            byte[] saltBytes = !string.IsNullOrEmpty(salt) ? Encoding.UTF8.GetBytes(salt) : new byte[0];
            using (var sha512 = SHA256.Create())
            {
                byte[] pswBytes = Encoding.UTF8.GetBytes(password);
                pswBytes = sha512.ComputeHash(pswBytes);
                return Convert.ToBase64String(pswBytes.Concat(saltBytes).ToArray());
            }
        }
    }
}
